#include "offlinemsgmodel.hpp"
#include "db.hpp"

void OfflineMsgModel::insert(int userid, const std::string &msg)
{
    // 1. 组装sql语句
    char sql[1024] = {0};
    sprintf(sql, "insert into offlinemessage values (%d, '%s')", userid, msg.c_str());

    // 2. 连接数据库
    MySQL mysql;
    if (mysql.connect())
    {
        mysql.update(sql);
    }
}

void OfflineMsgModel::remove(int userid)
{
    // 1. 组装sql语句
    char sql[1024] = {0};
    sprintf(sql, "delete from offlinemessage where userid = %d", userid);

    // 2. 连接数据库
    MySQL mysql;
    if (mysql.connect())
    {
        mysql.update(sql);
    }
}

std::vector<std::string> OfflineMsgModel::query(int userid)
{
    // 1. 组装sql语句
    char sql[1024] = {0};
    sprintf(sql, "select message from offlinemessage where userid = %d", userid);

    // 2. 连接数据库
    std::vector<std::string> ret;
    MySQL mysql;
    if (mysql.connect())
    {
        MYSQL_RES *res = mysql.query(sql);
        if (nullptr != res)
        {
            MYSQL_ROW row;
            while (nullptr != (row = mysql_fetch_row(res)))
            {
                ret.push_back(row[0]);
            }

            mysql_free_result(res);
        }
    }
    return ret;
}
